package thread;


class Counter {
    public int count = 0;

    synchronized  public void add(){
        count++;
    }
    //等价于，下面，synchronized的对象是this
//    public void add() {
//        //可以在这里加锁
//        synchronized (this) {
//            count++;
//        }
//    }

}

public class Demo19 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //上面已经加过锁了，这里也加锁，会产生死锁现象(但java做了特殊处理，故这里运行还是okay的)
//                synchronized (counter) {
//                    counter.add();
//                }
                counter.add();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                synchronized (counter) {
//                    counter.add();
//                }
                counter.add();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("counter=" + counter.count);

    }
}

